import React, { useState, useEffect } from 'react';
import { PersonalizationSettings as PersonalizationSettingsType, validatePersonalizationSettings, THEME_OPTIONS, LANGUAGE_OPTIONS, DATE_FORMAT_OPTIONS, TIME_FORMAT_OPTIONS } from './SettingsTypes';

interface PersonalizationSettingsProps {
  initialSettings: PersonalizationSettingsType;
  onSettingsChange: (settings: PersonalizationSettingsType) => void;
}

const PersonalizationSettings: React.FC<PersonalizationSettingsProps> = ({ initialSettings, onSettingsChange }) => {
  const [settings, setSettings] = useState<PersonalizationSettingsType>(initialSettings);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [isDirty, setIsDirty] = useState(false);
  
  // 初始化设置
  useEffect(() => {
    setSettings(initialSettings);
    setIsDirty(false);
    setErrors({});
  }, [initialSettings]);

  // 处理设置变更
  const handleChange = (field: keyof PersonalizationSettingsType, value: any) => {
    setIsDirty(true);
    setSettings(prev => ({ ...prev, [field]: value }));
    
    // 清除相关错误
    if (errors[field as string]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field as string];
        return newErrors;
      });
    }
  };

  // 处理保存
  const handleSave = () => {
    const validationErrors = validatePersonalizationSettings(settings);
    if (Object.keys(validationErrors).length === 0) {
      const updatedSettings = {
        ...settings,
        lastUpdated: new Date().toISOString()
      };
      
      onSettingsChange(updatedSettings);
      
      // 保存到本地存储
      localStorage.setItem('personalizationSettings', JSON.stringify(updatedSettings));
      localStorage.setItem('theme', settings.theme);
      localStorage.setItem('language', settings.language);
      
      setIsDirty(false);
      alert('个性化设置已成功保存！');
    } else {
      setErrors(validationErrors);
    }
  };

  // 处理重置
  const handleReset = () => {
    setSettings(initialSettings);
    setErrors({});
    setIsDirty(false);
  };

  // 生成主题预览
  const generateThemePreview = () => {
    const themeClass = settings.theme === 'system'
      ? (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
      : settings.theme;
      
    return (
      <div className={`theme-preview ${themeClass}`}>
        <div className="preview-header" />
        <div className="preview-content">
          <div className="preview-item" />
          <div className="preview-item" />
          <div className="preview-item" />
        </div>
      </div>
    );
  };

  return (
    <div className="personalization-settings">
      <h2>个性化设置</h2>
      
      <div className="settings-section">
        <h3>外观</h3>
        
        <div className="setting-group">
          <label className="setting-label">
            主题模式 <span className="required">*</span>
          </label>
          <div className="theme-options">
            {THEME_OPTIONS.map((option) => (
              <label key={option.value} className={`theme-option ${settings.theme === option.value ? 'active' : ''}`}>
                <input
                  type="radio"
                  name="theme"
                  value={option.value}
                  checked={settings.theme === option.value}
                  onChange={(e) => handleChange('theme', e.target.value)}
                />
                <span>{option.label}</span>
              </label>
            ))}
          </div>
          {errors.theme && <span className="error-message">{errors.theme}</span>}
          <div className="theme-preview-container">
            {generateThemePreview()}
          </div>
          <p className="setting-description">选择应用的主题模式，系统会根据系统设置自动切换明暗主题</p>
        </div>
        
        <div className="setting-group">
          <label className="setting-checkbox-label">
            <input
              type="checkbox"
              checked={settings.enableAnimation}
              onChange={(e) => handleChange('enableAnimation', e.target.checked)}
            />
            <span>启用动画效果</span>
          </label>
          <p className="setting-description">启用或禁用界面中的过渡动画和交互效果</p>
        </div>
      </div>

      <div className="settings-section">
        <h3>语言和本地化</h3>
        
        <div className="setting-group">
          <label className="setting-label">
            语言 <span className="required">*</span>
          </label>
          <select
            value={settings.language}
            onChange={(e) => handleChange('language', e.target.value)}
            className={`setting-select ${errors.language ? 'error' : ''}`}
          >
            {LANGUAGE_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          {errors.language && <span className="error-message">{errors.language}</span>}
          <p className="setting-description">选择系统界面显示的语言</p>
        </div>

        <div className="setting-group">
          <label className="setting-label">日期格式</label>
          <select
            value={settings.dateFormat}
            onChange={(e) => handleChange('dateFormat', e.target.value)}
            className="setting-select"
          >
            {DATE_FORMAT_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <p className="setting-description">系统中日期的显示格式</p>
        </div>

        <div className="setting-group">
          <label className="setting-label">时间格式</label>
          <select
            value={settings.timeFormat}
            onChange={(e) => handleChange('timeFormat', e.target.value)}
            className="setting-select"
          >
            {TIME_FORMAT_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <p className="setting-description">系统中时间的显示格式</p>
        </div>
      </div>

      <div className="settings-section">
        <h3>通知设置</h3>
        
        <div className="setting-group">
          <label className="setting-checkbox-label">
            <input
              type="checkbox"
              checked={settings.showNotifications}
              onChange={(e) => handleChange('showNotifications', e.target.checked)}
            />
            <span>显示通知</span>
          </label>
          <p className="setting-description">启用或禁用系统通知</p>
        </div>
      </div>

      <div className="settings-actions">
        <button
          type="button"
          className="btn-reset"
          onClick={handleReset}
          disabled={!isDirty}
        >
          重置
        </button>
        <button
          type="button"
          className="btn-save"
          onClick={handleSave}
          disabled={Object.keys(errors).length > 0 || !isDirty}
        >
          保存设置
        </button>
      </div>

      <div className="settings-note">
        <p>注意事项：</p>
        <p>• 主题和语言设置会立即生效，但某些设置可能需要刷新页面才能完全应用</p>
        <p>• 选择「系统」主题时，应用会根据操作系统的显示设置自动切换明暗模式</p>
        <p>• 禁用动画效果可能会提升在较低配置设备上的性能</p>
        <p>• 所有个性化设置都保存在本地浏览器中，更换设备或清除缓存后需要重新设置</p>
      </div>
    </div>
  );
};

export default PersonalizationSettings;